package com.avantis.admin.config.shiro;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;


/**
 * @author tracywang
 * Created by tracywang on 2018/11/12
 */
public class JwtUtils {

    //token的截止日期 7天
    private static long EXPIRE_TIME=7*24*60*60*1000 ;

    private static final String SECRET="PHP_IS_THE_BEST_LANGUAGE";

    //token在Redis的ttl 6个小时
    public static final Integer REDIS_TOKEN_EXPIRE = 6*60*60*1000;

    public static final String KEY_PREFIX = "GM_COCKPIT_";

    /**
     * 生成签名,7天后过期
     * @param account 通用工号
     * @return 加密的token
     */
    public static String sign(String account) {
        try {
            Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            // 附带username信息
            return JWT.create()
                    .withClaim("userId", account)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    /**
     * 校验token是否正确
     * @param token 密钥
     * @return 是否正确
     */
    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     * @param  claim 即生成token sign 中带入的 claim 字段 userId
     * @return token中包含的用户名
     */
    public static String getClaim(String token,String claim) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(claim).asString();
        } catch (JWTDecodeException e) {
            throw new RuntimeException(e);
        }
    }

}
